import cls from 'classnames';
import { useRef } from 'react';
import { Resizable } from 'react-resizable';
import '../../style.less';
import { ColumnConst } from '../../shared';
import { ColumnType } from 'rc-table/lib/interface';
import { RecordType } from '../../interfaces';

const ResizableTitle = (props: any) => {
  const { dataIndex, onResize, width, onClick, columns, ...restProps } = props;

  const draggingRef = useRef(false);

  const last = columns?.[columns?.length - 1];
  if (
    !width ||
    dataIndex === ColumnConst.index ||
    dataIndex === (last as ColumnType<RecordType>)?.dataIndex
  ) {
    return <th {...restProps} width={width} onClick={onClick} />;
  }

  return (
    <Resizable
      width={width < 100 ? 100 : width}
      height={0}
      handle={
        <span
          className={cls(['react-resizable-handle'])}
          onClick={(e) => {
            e.stopPropagation();
            e.preventDefault();
          }}
        />
      }
      onResizeStart={() => {
        draggingRef.current = true;
      }}
      onResize={onResize}
      onResizeStop={() => {
        draggingRef.current = false;
      }}
      draggableOpts={{ enableUserSelectHack: false }}
    >
      <th
        {...restProps}
        onClick={(...args) => {
          if (draggingRef.current) {
            return;
          }
          onClick?.(args);
        }}
      />
    </Resizable>
  );
};

export default ResizableTitle;
